package tw.arduino.view;

import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import com.swtdesigner.SWTResourceManager;

import org.eclipse.swt.custom.LineBackgroundEvent;
import org.eclipse.swt.custom.LineBackgroundListener;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import tw.arduino.control.InitCOM;
import tw.arduino.module.PublicObj;
import tw.arduino.module.RS232;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
/**
 * @ArduinoTW Command Center
 * @author XLINX x
 * @since 2010.08.08
 * @see http://arduino.tw
 */

public class TerminalComposite extends Composite implements Observer{
	static Logger log;
	private Text text;
	private Button btnHex;
	private Button btnOpenPort;
	private StyledText hexStyledText;
	private StyledText charStyledText;
	Thread initComT;// =new Thread(new InitCOM());;
	private Button tltmKeepupdate;
	public StringBuffer charSB = new StringBuffer("");
	public StringBuffer hexSB = new StringBuffer("");
	private Text txtd;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public String getStringToHex(String strValue) {
		byte byteData[] = null;
		int intHex = 0;
		String strHex = "";
		String strReturn = "";
		try {
			byteData = strValue.getBytes("ISO8859-1");
			for (int intI = 0; intI < byteData.length; intI++) {
				intHex = (int) byteData[intI];
				if (intHex < 0)
					intHex += 256;
				if (intHex < 16)
					strHex += "0" + Integer.toHexString(intHex).toUpperCase();
				else
					strHex += Integer.toHexString(intHex).toUpperCase();
				if (intHex == 13)
					strHex += "\n";
				strHex += " ";
			}
			strReturn = strHex;

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return strReturn;
	}

	public String getHexToString(String strValue) {
		int intCounts = strValue.length() / 2;
		String strReturn = "";
		String strHex = "";
		int intHex = 0;
		byte byteData[] = new byte[intCounts];
		try {
			for (int intI = 0; intI < intCounts; intI++) {
				strHex = strValue.substring(0, 2);
				strValue = strValue.substring(2);
				intHex = Integer.parseInt(strHex, 16);
				if (intHex > 128)
					intHex = intHex - 256;
				byteData[intI] = (byte) intHex;
			}
			strReturn = new String(byteData, "ISO8859-1");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return strReturn;
	}
	public void update(Observable o, Object arg) {
		updateRS232dataLog((byte[]) arg);
	}
	public void updateRS232dataLog(final byte[] value) {
		try {
			MainFrame.display.syncExec(new Runnable() {
				public void run() {
					if (tltmKeepupdate.getSelection()) {
						// MainFrame.lblRxTxbytes.setText("Rx:"+PublicObj.numRx+" Tx:"+PublicObj.numTx+" (bytes)");
						charStyledText.setForeground(SWTResourceManager
								.getColor(SWT.COLOR_BLUE));
						hexStyledText.setForeground(SWTResourceManager
								.getColor(SWT.COLOR_BLUE));

						charStyledText.append(new String(value));
						hexStyledText.append(getStringToHex(new String(value)));
						
						 hexStyledText.setSelection(hexStyledText.getText().length());
						 charStyledText.setSelection(charStyledText.getText().length());
//						 hexStyledText.showSelection();
						 
						if (charStyledText.getLineCount() > 99
								|| hexStyledText.getLineCount() > 99) {
							 charStyledText.setText("");
							 hexStyledText.setText("");
						}
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public TerminalComposite(Composite parent, int style) {
		super(parent, style);
		log = Logger.getLogger(this.getClass().getName());
		setLayout(new GridLayout());

		Composite group = new Composite(this, SWT.NONE);
		group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		group.setLayout(new GridLayout(3, false));

		Group grpControl = new Group(group, SWT.NONE);
		grpControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false,
				1, 1));
		grpControl.setText("Control");
		grpControl.setLayout(new GridLayout(2, false));

		btnOpenPort = new Button(grpControl, SWT.TOGGLE);
		btnOpenPort.setText("OpenPort");
		btnOpenPort.setImage(SWTResourceManager.getImage(
				TerminalComposite.class, "/images/gif/synch_participants.gif"));
		btnOpenPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		btnOpenPort.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (btnOpenPort.getSelection()) {
					if (MainFrame.pcSettingC.setAllComSetting()) {
						btnOpenPort.setImage(SWTResourceManager.getImage(
								TerminalComposite.class,
								"/images/gif/synch_participantsD.gif"));
						btnOpenPort.setText("ClosePort");
						initComT = new Thread(new InitCOM());
						initComT.start();
					} else {
						btnOpenPort.setSelection(false);
						MainFrame.statusLabel
								.setText("[Warring]Select PC-Setting Com First");
						log.debug("COM Select Error");
					}
				} else {
					btnOpenPort.setImage(SWTResourceManager.getImage(
							TerminalComposite.class,
							"/images/gif/synch_participants.gif"));
					btnOpenPort.setText("OpenPort");
					if (initComT != null)
						initComT.interrupt();
				}
			}
		});

		tltmKeepupdate = new Button(grpControl, SWT.TOGGLE);
		tltmKeepupdate.setImage(SWTResourceManager.getImage(
				TerminalComposite.class, "/images/gif/repository-synchronize.gif"));
		tltmKeepupdate.setSelection(true);
		tltmKeepupdate.setText("ReFresh");

		Group grpSendCmd = new Group(group, SWT.NONE);
		grpSendCmd.setText("Send Cmd");
		grpSendCmd.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false,
				1, 1));
		grpSendCmd.setLayout(new GridLayout(4, false));

		btnHex = new Button(grpSendCmd, SWT.RADIO);
		btnHex.setText("Hex");

		Button btnAscii = new Button(grpSendCmd, SWT.RADIO);
		btnAscii.setSelection(true);
		btnAscii.setText("ASCII");

		text = new Text(grpSendCmd, SWT.BORDER);
		text.addVerifyListener(new VerifyListener() {
			public void verifyText(VerifyEvent event) {
				String text = event.text.toUpperCase();
				text = text.replace('X', 'x');
				if (!text.matches("[0-9A-Fx]*")) {
					event.doit = false;
				}
				event.text = text;
			}
		});
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

		Button btnSend = new Button(grpSendCmd, SWT.NONE);
		btnSend.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String cmd = text.getText();

				if (btnHex.getEnabled()) {
					if (text.getText().length() > 1) {
						if (text.getText().length() % 2 != 0) {
							cmd.substring(0, cmd.length() - 1);
							text.setText(cmd);
						}
						for (int i = 0; i < cmd.length(); i++) {

						}

					}
				} else {// ASCII mode
					for (int i = 0; i < cmd.length(); i++) {
						// PublicObj.initCom.s
					}
				}
			}
		});
		btnSend.setText("Send");

		Group grpCustReturn = new Group(group, SWT.NONE);
		grpCustReturn.setText("Cust. Return");
		grpCustReturn.setLayout(new GridLayout(1, false));
		grpCustReturn.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false,
				false, 1, 1));

		txtd = new Text(grpCustReturn, SWT.BORDER);
		txtd.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		txtd.setText("0D");
		txtd.setBounds(0, 0, 71, 18);

		Group grpData = new Group(this, SWT.NONE);
		grpData.setText("Data");
		grpData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		grpData.setLayout(new GridLayout(1, false));

		SashForm sashForm = new SashForm(grpData, SWT.NONE);
		sashForm.setOrientation(SWT.HORIZONTAL);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));

		Composite composite = new Composite(sashForm, SWT.NONE);
		composite.setLayout(new GridLayout(1, false));

		charStyledText = new StyledText(composite, SWT.WRAP
				| SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
		charStyledText.setWordWrap(true);
		// charStyledText = new StyledText(composite, SWT.BORDER |
		// SWT.FULL_SELECTION | SWT.WRAP);
		charStyledText.addVerifyListener(new VerifyListener() {
			public void verifyText(VerifyEvent arg0) {

			}
		});
		charStyledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		charStyledText.addLineBackgroundListener(new LineBackgroundListener() {
			public void lineGetBackground(LineBackgroundEvent arg0) {
				if (charStyledText.getLineAtOffset(arg0.lineOffset) % 2 == 1)
					arg0.lineBackground = Display.getCurrent().getSystemColor(
							SWT.COLOR_INFO_BACKGROUND);

			}
		});
		Composite composite_1 = new Composite(sashForm, SWT.NONE);
		composite_1.setLayout(new GridLayout(1, false));

		hexStyledText = new StyledText(composite_1, SWT.WRAP
				| SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
		// hexStyledText = new StyledText(composite_1, SWT.BORDER |
		// SWT.FULL_SELECTION | SWT.WRAP);
		hexStyledText.setWordWrap(true);
		hexStyledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		hexStyledText.addLineBackgroundListener(new LineBackgroundListener() {
			public void lineGetBackground(LineBackgroundEvent arg0) {
				if (hexStyledText.getLineAtOffset(arg0.lineOffset) % 2 == 1)
					arg0.lineBackground = Display.getCurrent().getSystemColor(
							SWT.COLOR_INFO_BACKGROUND);

			}
		});
		sashForm.setWeights(new int[] { 25, 75 });
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
